const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');

const app = express();

/* 引入cors */
const cors = require('cors');
// app.use(cors());

/* 引入body-parser */
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

/* 引入mysql */
const mysql = require('mysql');
global.conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'test',
    multipleStatements: true
})
conn.connect((err) => {
    if (err) {
        console.error('数据库连接失败:', err.stack);
        return;
    }
    console.log('已连接到数据库，ID:', conn.threadId);
});


// 查看引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// 捕获404并且转发给错误处理程序
app.use(function (req, res, next) {
    next(createError(404));
});

// 错误处理
app.use(function (err, req, res, next) {
    //设置局部变量，只在开发中提供错误
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // 错误页面
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
